package com.qiqichangting.changting.utils;

import org.apache.commons.lang3.StringEscapeUtils;


import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils extends org.apache.commons.lang3.StringUtils{
    private static final String CHARSET_NAME = "UTF-8";

    // 首字母转小写
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    // 首字母转大写
    public static String toUpperCaseFirstOne(String s) {

        if (Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    /**
     * 判断是否是空字符串
     *
     * @author Robin Chang
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        if (s != null && !s.equals("")) {
            return true;
        }

        return false;
    }

    public static boolean isNull(String string) {

        if (string == null || string.isEmpty()) {
            return false;
        }
        return true;

    }


    public static void printJson(HttpServletResponse response, String content) {
        try {
            response.reset();
            response.setContentType("application/json");
            response.setHeader("Cache-Control", "no-store");
            response.setCharacterEncoding("UTF-8");
            PrintWriter pw = response.getWriter();
            pw.write(content);
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否为数字
     *
     * @Title: isNumeric
     * @Description: 判断是否为数字
     * @param str
     * @return
     * @return: boolean
     */
    public static boolean isNumeric(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     *
     * @title: camelToUnderline
     * @description: 驼峰转下划线
     * @param param
     * @return
     * @return: String
     */
    public static String camelToUnderline(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append('_');
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     *
     * @title: underlineToCamel
     * @description:下划线转驼峰
     * @param param
     * @return
     * @return: String
     */
    public static String underlineToCamel(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (c == '_') {
                if (++i < len) {
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * A hashing method that changes a string (like a URL) into a hash suitable
     * for using as a disk filename.
     */
    public static String hashKeyForDisk(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private static String bytesToHexString(byte[] bytes) {
        // http://stackoverflow.com/questions/332079
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     *
     * @title: getExtensionName
     * @description: Java文件操作 获取文件扩展名
     * @param filename
     * @return
     * @return: String
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     *
     * @title: getFileNameNoEx
     * @description: Java文件操作 获取不带扩展名的文件名
     * @param filename
     * @return
     * @return: String
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }



    public static boolean isNumericAndDot(String str) {
        if (str == null || str.trim().equals("")) {
            return false;
        }
        Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]*([Ee]{1}[0-9]+)?");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 去除字符串首尾出现的某个字符.
     *
     * @param source
     *            源字符串.
     * @param element
     *            需要去除的字符.
     * @return String.
     */
    public static String trimFirstAndLastChar(String source, char element) {
        boolean beginIndexFlag = true;
        boolean endIndexFlag = true;
        do {
            int beginIndex = source.indexOf(element) == 0 ? 1 : 0;
            int endIndex = source.lastIndexOf(element) + 1 == source.length() ? source.lastIndexOf(element)
                    : source.length();
            source = source.substring(beginIndex, endIndex);
            beginIndexFlag = (source.indexOf(element) == 0);
            endIndexFlag = (source.lastIndexOf(element) + 1 == source.length());
        } while (beginIndexFlag || endIndexFlag);
        return source;
    }

    /**
     * 缩略字符串（不区分中英文字符）
     *
     * @param str
     *            目标字符串
     * @param length
     *            截取长度
     * @return
     */
    public static String abbr(String str, int length) {
        if (str == null) {
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            int currentLength = 0;
            for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
                currentLength += String.valueOf(c).getBytes("GBK").length;
                if (currentLength <= length - 3) {
                    sb.append(c);
                } else {
                    sb.append("...");
                    break;
                }
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 替换掉HTML标签方法
     */
    public static String replaceHtml(String html) {
        if (isBlank(html)) {
            return "";
        }
        String regEx = "<.+?>";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(html);
        String s = m.replaceAll("");
        return s;
    }

    /**
     * 转换为字节数组
     *
     * @param bytes
     * @return
     */
    public static String toString(byte[] bytes) {
        try {
            return new String(bytes, CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            return EMPTY;
        }
    }

    /**
     * 转换为字节数组
     *
     * @param str
     * @return
     */
    public static byte[] getBytes(String str) {
        if (str != null) {
            try {
                return str.getBytes(CHARSET_NAME);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 判断是否为姓名
     *
     * @param x
     * @return
     */
    public boolean isprime(int x) // 检验算法优化
    {
        if (x <= 1 || (x % 2 == 0))
            return false;// x&1 <=> x%2
        int i = 3;
        while (i <= x) // sqrt(x) + 1 => x .ok
        {
            if (x % i <= 0)
                return false;
            i += 2;
        }
        return true;
    }
    /**
     * 获取现在的时间 年-月-日 时分秒
     */
    public static String getNowTime() {
        String timestampPattern = "yyyy-MM-dd HH:mm:ss";
        return new SimpleDateFormat(timestampPattern)
                .format(new Date());
    }
    /**
     * 获取订单前缀
     */
    public static String getOrderPrefix(String area) {
        String perfix="";
        String timestampPattern = "yyyyMMdd";
        String day = new SimpleDateFormat(timestampPattern)
                .format(new Date());
        if (area!=null) {
            int len=area.length();
            if (len<8) {
                int len0 = 8-len;
                String str ="";
                for(int i=0;i<len0;i++) {
                    str+="0";
                }
                area = str+area;
            }
        }else {
            area ="00000000";
        }
        perfix="D"+day+area;
        return perfix;
    }
    public static String getOrderSuffix(String bh) {
        String suffix =bh.substring(bh.length()-3,bh.length());
        int i = Integer.parseInt(suffix)+1;
        if (i<=9) {
            suffix = "00"+i;
        }else if(i>9&&i<=99){
            suffix = "0"+i;
        }else {
            suffix=""+i;
        }
        return suffix;
    }
    public static int getMIn(String stime,String etime) {
        int minutes=0;
        try {
            SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            /*分钟差*/
            Date fromDate3 = simpleFormat.parse(stime);
            Date toDate3 = simpleFormat.parse(etime);
            long from3 = fromDate3.getTime();
            long to3 = toDate3.getTime();
            minutes = (int) ((to3 - from3) / (1000 * 60));
            System.out.println("两个时间之间的分钟差为：" + minutes);
            return minutes;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return minutes;

    }

}
